<template>
  <div v-loading="loading" :style="{height: (isBulkData ? '60vh' : '50vh')}">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('权限类型')" prop="type">
            <el-radio-group v-model="form.type" :placeholder="$t('权限类型')">
              <el-radio label="download">{{ $t('查看 + 下载') }}</el-radio>
              <el-radio label="view">{{ $t('查看') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col v-if="isBulkData" :span="24">
          <el-form-item :label="$t('可见出资人设置方式')" prop="settingMethod">
            <span slot="label">
              {{ $t('可见出资人设置方式') }}
              <el-tooltip placement="top">
                <div slot="content">
                  {{ $t('覆盖权限: 将会替换文件中原本设置的权限') }}
                  <br>
                  {{ $t('补充权限: 将选择的权限合并到原有的权限中') }}
                  <br>
                  {{ $t('当某出资人同时存在两种权限, 仅保留不可见出资人权限') }}
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-radio-group v-model="form.settingMethod" :placeholder="$t('设置方式')" @change="changeRatio($event, 'settingMethod')">
              <el-radio label="bc">{{ $t('补充权限') }}</el-radio>
              <el-radio label="fg">{{ $t('覆盖权限') }}</el-radio>
              <el-radio label="qk">{{ $t('清空权限') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('可见出资人')" prop="lpIdList">
            <span slot="label">
              {{ $t('可见出资人') }}
              <el-tooltip :content="$t('选中的出资人可查看或下载当前文件')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-select v-model="form.lpIdList" filterable clearable multiple collapse-tags :disabled="form.settingMethod === 'qk'" @change="changeEmail">
              <el-option
                v-for="item in lpListOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
                :disabled="form.lpIdNot.includes(item.dictValue)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="isBulkData" :span="24">
          <el-form-item :label="$t('不可见出资人设置方式')" prop="settingNotMethod">
            <span slot="label">
              {{ $t('不可见出资人设置方式') }}
              <el-tooltip placement="top">
                <div slot="content">
                  {{ $t('覆盖权限: 将会替换文件中原本设置的权限') }}
                  <br>
                  {{ $t('补充权限: 将选择的权限合并到原有的权限中') }}
                  <br>
                  {{ $t('当某出资人同时存在两种权限, 仅保留不可见出资人权限') }}
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-radio-group v-model="form.settingNotMethod" :placeholder="$t('设置方式')" @change="changeRatio($event, 'settingNotMethod')">
              <el-radio label="bc">{{ $t('补充权限') }}</el-radio>
              <el-radio label="fg">{{ $t('覆盖权限') }}</el-radio>
              <el-radio label="qk">{{ $t('清空权限') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('不可见出资人')" prop="lpIdNot">
            <span slot="label">
              {{ $t('不可见出资人') }}
              <el-tooltip :content="$t('选中的出资人不可查看且不可下载当前文件')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-select v-model="form.lpIdNot" filterable clearable multiple collapse-tags :disabled="form.settingNotMethod === 'qk'">
              <el-option
                v-for="item in lpListOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
                :disabled="form.lpIdList.includes(item.dictValue)"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="!isBulkData" :span="24">
          <el-form-item :label="$t('过期时间')" prop="expireDate">
            <el-date-picker
              v-model="form.expireDate"
              type="datetime"
              :picker-options="pickerOptions"
              format="yyyy-MM-dd HH:mm"
              :placeholder="$t('请填写过期时间, 不填不过期!')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('邮件通知')" prop="sendEmail">
            <el-radio-group v-model="form.sendEmail" :placeholder="$t('邮件通知')">
              <el-radio label="yes">{{ $t('发送') }}</el-radio>
              <el-radio label="no">{{ $t('不发送') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-dialog :title="$t('邮件通知')" :visible.sync="emailInfoOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="commentsDigOnly" append-to-body>
      <div v-loading="emailInfoLoading" style="padding: 20px;">
        <el-row>
          <el-col :span="24">
            <div>
              <div style="display: flex;">
                <label data-v-0a879dca="" for="type" class="el-form-item__label" style="width: 120px; text-align: left; line-height: 30px;">{{ $t('收件人') }}</label>
              </div>
              <el-tag
                v-for="tag in form.emailUser"
                :key="tag"
                closable
                :disable-transitions="false"
                @close="handleClose(tag)"
              >
                {{ tag }}
              </el-tag>
              <el-input
                v-if="inputVisible"
                ref="saveTagInput"
                v-model="inputValue"
                class="input-new-tag"
                size="small"
                style="width: 250px;"
                :placeholder="$t('录入邮箱或\'名称：邮箱\'格式录入')"
                @keyup.enter.native="handleInputConfirm"
                @blur="handleInputConfirm"
              />
              <el-button v-else class="button-new-tag" size="small" @click="showInput">+</el-button>
            </div>
          </el-col>
          <el-col :span="24">
            <div style="display: flex;">
              <label data-v-0a879dca="" for="type" class="el-form-item__label" style="width: 120px; text-align: left; line-height: 30px;">{{ $t('邮件内容') }}</label>
            </div>
            <EditorTxt v-if="!emailInfoLoading" v-model="form.emailMsg" :height="300" />
          </el-col>
        </el-row>
      </div>
      <div class="dialog-footer" style="text-align: right;position: absolute;right:15px;bottom: 15px;">
        <el-button @click="emailInfoOpen = false">{{ $t('取消') }}</el-button>
        <el-button type="primary" @click="sendEmailSubmitForm">{{ $t('发送') }}</el-button>
      </div>
    </el-dialog>
    <div class="dialog-footer" style="text-align: right;position: absolute;right: 3vh;bottom: 3vh;">
      <saveBtn>
        <template v-slot:before>
          <el-button v-if="!isEmpty(form.id)" type="warning" @click="deleteById">{{ $t('清除权限') }}</el-button>
        </template>
      </saveBtn>
    </div>
  </div>
</template>

<script>
import { findLpList } from '@/api/fund/lpBase/lpBase'
import {
  delFileDataRoomPermission,
  getEmailInfo,
  // getEmailInfoBulk,
  getPermissionByFileId,
  saveFileDataRoomPermission
} from '@/api/file/fileDataRoomPermission/fileDataRoomPermission'
import { listDict } from '@/api/fund/investor/fundInvestor'
import EditorTxt from '@/components/Tinymce'

export default {
  components: {
    EditorTxt
  },
  props: {},
  data() {
    return {
      // 遮盖层
      loading: false,
      form: {},
      rules: {
        // lpIdList: [{ required: true, message: this.$t('必填项'), trigger: 'blur' }],
        type: [{ required: true, message: this.$t('请选择权限类型'), trigger: 'blur' }]
      },
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now()
        }
      },
      lpListOptions: [],
      isBulkData: false,
      parentFileBase: {},
      emailInfoOpen: false,
      emailInfoLoading: false,
      inputVisible: false,
      inputValue: undefined
    }
  },
  watch: {},
  created() {
  },
  methods: {
    init(data) {
      this.loading = true
      this.isBulkData = false
      this.parentFileBase = data
      if (data && data.id) {
        this.loadSelectOption({})
        getPermissionByFileId(data.id).then(response => {
          if (response.data === null) {
            this.reset()
          } else {
            this.form = response.data
            if (this.isEmpty(this.form.lpIdList)) {
              this.form.lpIdList = []
            }
            if (this.isEmpty(this.form.lpIdNot)) {
              this.form.lpIdNot = []
            }
          }
          this.loading = false
        })
      } else {
        this.reset()
        this.loading = false
      }
    },
    bulkInit(ids) {
      console.log('批量修改文件dataRoom权限')
      this.isBulkData = true
      this.reset()
      this.form.fileId = undefined
      ids.forEach(item => {
        this.form.fileIdList.push(item.id || item.fileId)
      })
      this.loadSelectOption({})
    },
    loadSelectOption(data) {
      // 加载下拉内容
      if (data.businessId) {
        // 加载该基金下的
        listDict({ fundId: data.businessId }).then(response => {
          this.lpListOptions = response.data
        })
      } else {
        // 获取所有的 LP用户
        findLpList().then(response => {
          this.lpListOptions = response.data
        })
      }
    },
    cancel() {
      this.reset()
      this.loading = false
      this.emailInfoLoading = false
      this.$parent.$parent.openFilePermission = false
    },
    reset() {
      this.form = {
        type: 'download',
        lpIdList: [],
        lpIdNot: [],
        expireDate: undefined,
        settingMethod: 'bc',
        settingNotMethod: 'bc',
        sendEmail: 'no',
        fileId: this.parentFileBase ? this.parentFileBase.id : '',
        fileIdList: [],
        emailMsg: undefined
      }
      this.resetForm('form')
    },
    sendEmailSubmitForm() {
      var saveStatus = true
      if (this.isEmpty(this.form.emailUser)) {
        this.msgError(this.$t('收件人不能为空'))
        saveStatus = false
      }
      if (this.isEmpty(this.form.emailMsg)) {
        this.msgError(this.$t('邮件内容不能为空'))
        saveStatus = false
      }
      if (saveStatus) {
        this.emailInfoLoading = true
        this.submitFormSave()
      }
    },
    submitForm() {
      this.$refs['form'].validate(valid => {
        var flag = true
        if (this.isEmpty(this.form.lpIdList) && this.isEmpty(this.form.lpIdNot) && !this.isBulkData) {
          flag = false
          this.msgError(this.$t('请添加出资人'))
        }
        // 验证数据
        if (valid && flag) {
          if (this.form.sendEmail === 'yes') {
            this.sendEmailBtn()
          } else {
            this.submitFormSave()
          }
        } else {
          this.locationError(document)
        }
      })
    },
    submitFormSave() {
      this.loading = true
      saveFileDataRoomPermission(this.form).then(response => {
        if (response.code === 200) {
          this.msgSuccess(this.$t(response.msg))
          var data = response.data
          data.lpNames = this.lpListOptions.filter(item => {
            return data.lpIdList.includes(item.dictValue)
          }).map(item => {
            return item.dictLabel
          }).join(',')
          data.lpNotNames = this.lpListOptions.filter(item => {
            return data.lpIdNot.includes(item.dictValue)
          }).map(item => {
            return item.dictLabel
          }).join(',')
          this.$emit('saveFileDataRoom', data, this.isBulkData)
        } else {
          this.msgError(this.$t(response.msg))
        }
        this.cancel()
      }).catch(() => {
        this.msgError('error')
        this.loading = false
      })
    },
    changeRatio(val, type) {
      if (type === 'settingMethod') {
        this.form.lpIdList = []
      } else if (type === 'settingNotMethod') {
        this.form.lpIdNot = []
      }
    },
    /**
     * 发送邮件
     */
    sendEmailBtn() {
      this.emailInfoOpen = true
      this.emailInfoLoading = true
      this.$nextTick(() => {
        console.log('初始化')
        if (this.isEmpty(this.form.id) || this.isEmpty(this.form.emailMsg)) {
          // 新增
          var emailMsg = []
          var filter = this.lpListOptions.filter(obj => this.form.lpIdList.includes(obj.dictValue))
          if (filter) {
            filter.forEach(item => {
              if (!this.isEmpty(item.email)) {
                emailMsg.push(item.dictLabel + '：' + item.email)
              }
            })
          }
          this.form.emailUser = emailMsg
          // 获取默认的邮件模板
          // if (this.isBulkData) {
          //   getEmailInfoBulk(this.form).then(response => {
          //     this.form.emailMsg = response.data.context
          //     this.emailInfoLoading = false
          //   }).catch(() => {
          //     this.emailInfoLoading = false
          //   })
          // } else {
          getEmailInfo(this.form).then(response => {
            this.form.emailMsg = response.data.context
            this.emailInfoLoading = false
          }).catch(() => {
            this.emailInfoLoading = false
          })
          // }
        } else {
          this.emailInfoLoading = false
        }
      })
    },
    /**
     * 删除某个收件人
     * @param tag
     */
    handleClose(tag) {
      this.form.emailUser.splice(this.form.emailUser.indexOf(tag), 1)
      this.$forceUpdate()
    },
    /**
     * 打开新增收件人
     */
    showInput() {
      this.inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    /**
     * 添加收件人
     */
    handleInputConfirm() {
      var inputValue = this.inputValue
      if (inputValue) {
        // 校验邮箱
        inputValue = inputValue.replaceAll(':', '：')
        if (inputValue.includes('：')) {
          var arr = inputValue.split('：')
          if (arr.length === 2) {
            var email = arr[1]
            this.checkEmail(email, inputValue)
          } else {
            this.msgError(this.$t('格式不正确. 请直接填写邮箱或(名称：邮箱)的格式录入'))
          }
        } else {
          this.checkEmail(inputValue, inputValue)
        }
      } else {
        this.inputVisible = false
        this.inputValue = ''
      }
    },
    checkEmail(email, inputValue) {
      if (email.includes('@')) {
        var email2 = email.split('@')
        if (email2.length === 2) {
          if (email2[1].includes('.')) {
            this.form.emailUser.push(inputValue)
            this.inputVisible = false
            this.inputValue = ''
          } else {
            this.msgError(this.$t('邮箱格式不正确'))
          }
        } else {
          this.msgError(this.$t('邮箱格式不正确'))
        }
      } else {
        this.msgError(this.$t('邮箱格式不正确'))
      }
    },
    changeEmail(val) {
      if (this.isEmpty(this.form.emailUser)) {
        this.form.emailUser = []
      }
      var allLpName = []
      this.lpListOptions.forEach(item => {
        allLpName.push(item.dictLabel)
      })
      var deleteElement = []
      this.form.emailUser.forEach((item) => {
        var lpName = item.split('：')[0]
        if (allLpName.includes(lpName)) {
          deleteElement.push(item)
        }
      })
      this.form.emailUser = this.form.emailUser.filter(item => !deleteElement.includes(item))
      if (val) {
        var filter = this.lpListOptions.filter(obj => this.form.lpIdList.includes(obj.dictValue))
        if (filter) {
          filter.forEach(item => {
            if (!this.isEmpty(item.email)) {
              var temp = item.dictLabel + '：' + item.email
              if (!this.form.emailUser.includes(temp)) {
                this.form.emailUser.push(temp)
              }
            }
          })
        }
      }
    },
    // 清除权限
    deleteById() {
      var _this = this
      this.$confirm(this.$t('是否继续?'), this.$t('提示'), {
        confirmButtonText: this.$t('确定'),
        cancelButtonText: this.$t('取消'),
        type: 'warning'
      }).then(() => {
        _this.loading = true
        delFileDataRoomPermission(_this.form.id).then(response => {
          this.$emit('saveFileDataRoom', { fileId: _this.form.fileId, lpNames: undefined })
          this.msgInfo(response.msg)
          _this.cancel()
        })
      }).catch(() => {
      })
    }
  }
}
</script>

<style scoped lang="scss">
.dataForm{
  overflow: auto;
  height: 90%;
  margin-right: -20px;
}
.tooltip-data-room {
  padding: 8px;
}
/deep/ .el-tag--medium {
  min-width: 150px;
  margin: 0 5px 0 5px;
}
</style>
